let addNode = document.createElement('div');
addNode.style.textAlign = 'center';

let btn_id = 'SQS-douyin-download';
addNode.innerHTML = `<button id="${btn_id}" 
        style="
            position:fixed;
            color:rgb(255, 255, 255);
            background-color: rgba(0, 0, 0, 0);
            padding: 0.4rem;
            border-width: 0;
            font-size: 1.16rem;
            left:54.6%;
            bottom:16px;
            display:none;
            transform: translate(-50%);
            z-index:999999999;
            cursor: pointer;"
    >下载视频</button>
    `;

document.body.appendChild(addNode);

var btn = document.getElementById(btn_id);

let queue = [];
let limit_one_time = 10;
for (let i = 0; i < limit_one_time + 1; ++i) {
    queue[i] = null;
}

/**
 * 创建进度显示
 */
function creatShowDom() {
    let node = document.createElement('div');
    node.style.textAlign = 'center';
    let num = null;
    for (let i = 1; i < queue.length + 1; ++i) {
        if (queue[i] == null) {
            queue[i] = 1;
            num = i;
            break;
        }
    }
    if (num == null) {
        alert('最多同时下载' + limit_one_time + '个视频，请等待其他视频下载完成！');
    }
    node.innerHTML = `<span id="${num + 666666666}"
        style="
            position:fixed;
            left:54.6%;
            top:${60 + 40 * (num)}px;
            width:360px;
            height:36px;
            border-width:0rem;
            transform: translate(-50%);
            padding: 0.4rem;
            color:rgb(255, 255, 255);
            background-color:rgba(0,0,0,0.2);
            border-width: 0;
            z-index:999999999;
            font-size: 1.16rem;
            vertical-align: middle;
    "></span>`;
    document.body.appendChild(node);
    return node;
}

/**
 * 下载视频
 * @param {string} url 
 * @param {string} name 
 * @returns 
 */
function download(url, name) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.send(null);
    xhr.responseType = "blob";
    let show_dom = null;
    xhr.addEventListener('progress', e => {
        const percent = ((e.loaded / e.total) * 100).toFixed(2);
        if (show_dom === null) {
            // 创建节点
            show_dom = creatShowDom();
        } else if (show_dom && percent >= 100) {
            show_dom.childNodes[0].innerText = `已下载:${percent}%`;
            let num = show_dom.childNodes[0].id - 666666666;
            queue[num] = null;
            // 移除节点
            show_dom.remove();
        } else if (show_dom && percent < 100) {
            show_dom.childNodes[0].innerText = `已下载:${percent}%`;
        }
    }, false);

    xhr.onreadystatechange = (e) => {
        if (xhr.status == 200) {
            if (xhr.response) {
                const a = document.createElement('a');
                a.download = name;
                a.href = URL.createObjectURL(new Blob([xhr.response], { type: 'video/mpeg4' }));
                a.click();
                URL.revokeObjectURL(a.href);
            }
        } else if (response.status == 404) {
            if (show_dom) {
                let num = show_dom.childNodes[0].id - 666666666;
                queue[num] = null;
            }
            downloadError();
        } else if (response.status == 500) {
            if (show_dom) {
                let num = show_dom.childNodes[0].id - 666666666;
                queue[num] = null;
            }
            downloadError();
        }
    }
}

/**
 * 日期获取
 */
function dateFormat() {
    date = new Date();
    var year = date.getFullYear();                // 年
    var month = showTime(date.getMonth() + 1);        // 月
    var day = showTime(date.getDate());          // 日
    var hours = showTime(date.getHours());         // 小时
    var minutes = showTime(date.getMinutes());    // 分钟
    var second = showTime(date.getSeconds());     // 秒
    var str = '';
    str = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + second
    return str;
}

/**
 * 不够两位数就补零
 * @param {str} time 
 * @return {str} time 
 */
function showTime(t) {
    var time;
    time = t > 10 ? t : '0' + t;
    return time;
}



/**
 * 失败提示
 */
function downloadError() {
    alert('下载失败');
}

/**
 * DFS获取视频标题
 * @param {object} node 
 * @returns 
 */
function dfs(node) {
    let txt = node.innerText ? node.innerText : '';
    if (txt) {
        return txt;
    }
    node.childNodes.forEach(tem_node => {
        txt += dfs(tem_node);
    });
    return txt;
}

/**
 * 下载视频并命名
 * @param {number} length 
 * @param {object} title 
 * @param {object} video_box 
 * @returns 
 */
function downloadVideoAndRename(length, title, video_box,) {
    if (length != 1 && length != 3) {
        downloadError();
        return;
    }
    title = title[length == 1 ? 0 : 1]
        .childNodes[0]
        .childNodes[1]
        .childNodes[0]
        .childNodes[0]
        .childNodes[1]
        .childNodes[0]
        ;
    title = dfs(title);
    title ? title : title = '抖音 ' + dateFormat();
    if (length == 1) {
        download(video_box[0].childNodes[0].src, title + '.mp4');
    } else {
        download(video_box[1].childNodes[0].src, title + '.mp4');
    }
}


function listenUrl() {
    setInterval(() => {
        btn.style.display = 'none';
        let url = window.location.href;
        judgeUrl(url);
    }, 666);
}

listenUrl();

btn.addEventListener("click", () => {
    let title = document.querySelectorAll('#video-info-wrap')
    let video_box = document.getElementsByTagName('video');
    downloadVideoAndRename(video_box.length, title, video_box);
})


/**
 * 判断是否时可以下载视频的页面
 */
function judgeUrl(url) {
    if (url.indexOf('?modal_id=') == -1) {
        if (url == 'https://www.douyin.com' ||
            url == 'https://www.douyin.com/' ||
            url == 'https://www.douyin.com/friend' ||
            url == 'https://www.douyin.com/friend/' ||
            url == 'https://www.douyin.com/follow' ||
            url == 'https://www.douyin.com/follow/'
        ) {
            // 显示按钮
            btn.style.bottom = '16px';
            btn.style.left = '54.6%';
            btn.style.display = 'block';
        } else {
            // 隐藏按钮
            btn.style.display = 'none';
        }
    } else {
        // 显示按钮
        btn.style.bottom = '6px';
        btn.style.left = '50%';
        btn.style.display = 'block';
    }
}